// util
package util

import (
	"bytes"
	"encoding/gob"
	"strconv"
	"strings"
)

func DeepCopy(dst, src interface{}) error {
	var buf bytes.Buffer

	if err := gob.NewEncoder(&buf).Encode(src); err != nil {
		return err
	}
	return gob.NewDecoder(bytes.NewBuffer(buf.Bytes())).Decode(dst)
}

func String(a interface{}) (string, bool) {

	if v, p := a.(int); p {
		return strconv.Itoa(v), p
	}
	if v, p := a.(float64); p {
		return strconv.FormatFloat(v, 'f', -1, 64), p
	}

	if v, p := a.(float32); p {
		return strconv.FormatFloat(float64(v), 'f', -1, 32), p
	}

	if v, p := a.(int16); p {
		return strconv.Itoa(int(v)), p
	}
	if v, p := a.(uint); p {
		return strconv.Itoa(int(v)), p
	}
	if v, p := a.(int32); p {
		return strconv.Itoa(int(v)), p
	}
	if v, p := a.([]byte); p {
		for i := 0; i < len(v); i++ {
			if v[i] == 0 {
				return string(v[0:i]), p
			}
		}
		return string(v), p
	}
	return "", false
}

func GetIpFromIPort(iport string) string {
	var ret string
	ipPort := strings.Split(iport, ":")
	if len(ipPort) != 2 {
		ret = iport
	} else {
		ret = ipPort[0]
	}
	return ret
}
